from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
import time
import logging

logger = logging.getLogger(__name__)


async def logging_middleware(request: Request, call_next):
    """日志记录中间件"""
    start_time = time.time()
    
    # 记录请求信息
    logger.info(f"请求: {request.method} {request.url}")
    logger.debug(f"请求头: {dict(request.headers)}")
    
    # 处理请求
    response = await call_next(request)
    
    # 计算请求处理时间
    process_time = time.time() - start_time
    logger.info(f"响应: {request.method} {request.url} {response.status_code} {process_time:.4f}s")
    
    # 添加处理时间到响应头
    response.headers["X-Process-Time"] = str(process_time)
    
    return response


def setup_middleware(app: FastAPI):
    """设置应用中间件"""
    # 添加CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.BACKEND_CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 添加日志记录中间件（在调试模式下启用）
    if settings.DEBUG:
        app.middleware("http")(logging_middleware)
        
    # 可以根据需要添加更多中间件
    # 例如: 认证中间件、请求限流中间件等